package gamesorter2;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author th3ory
 */
public class TheSorter {
    LinkedList<String> allGames;
    LinkedList<String> rankedGames;
    
    Random generator;
    
    Scanner user_input;
    
    public TheSorter() {
        init();
        //sortMe(0, allGames);
        //displayRankings();
    }
    
    public void startSorting() {
        sortMe(0, allGames);
        displayRankings();
    }
    
    private void init() {
        allGames = new LinkedList<>();
        rankedGames = new LinkedList<>();
        
        generator = new Random();
        
        user_input = new Scanner( System.in );
    }
    
    public void setGames(List games) {
        init();
        allGames.clear();
        allGames.addAll(games);
    }
    
    
    
    private void sortMe(int index, LinkedList<String> toBeSorted) {
        if(toBeSorted.isEmpty())
            return;
        LinkedList<String> gamesBetter = new LinkedList<>();
        LinkedList<String> gamesWorse = new LinkedList<>();
        
        int randomNum = generator.nextInt(toBeSorted.size());
        String selectedGame = toBeSorted.get(randomNum);
        toBeSorted.remove(randomNum);
        rankedGames.add(index, selectedGame);
        if(toBeSorted.isEmpty())
            return;
        for(String s: toBeSorted) {
            System.out.println("Is " + s + " better or worse than " + selectedGame + "? ");
            String answer = user_input.next();
            if(answer.equalsIgnoreCase("b"))
                gamesBetter.add(s);
            else
                gamesWorse.add(s);
        }
        sortMe(rankedGames.indexOf(selectedGame), gamesBetter);
        sortMe(rankedGames.indexOf(selectedGame) + 1, gamesWorse);
    }

    private void displayRankings() {
        int i = 1;
        for(String game: rankedGames) {
            System.out.println(i++ + ". " + game);
        }
    }
}
